package com.aorise.service.system.impl;

import com.aorise.mapper.system.AuthorityMapper;
import com.aorise.mapper.system.RoleAuthorityMapper;
import com.aorise.model.system.Authority;
import com.aorise.model.system.AuthorityExample;
import com.aorise.model.system.RoleAuthority;
import com.aorise.model.system.RoleAuthorityExample;
import com.aorise.service.system.AuthorityService;
import com.aorise.utils.ConstDefine;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: zhouhao
 * @Date: 2019/4/26
 * @Description:
 */
@Service
public class AuthorityServiceImpl implements AuthorityService {

    @Autowired
    AuthorityMapper authorityMapper;

    @Autowired
    RoleAuthorityMapper roleAuthorityMapper;

    public List<Authority> selectByRoleIds(List<Integer> roleIds){

        RoleAuthorityExample roleAuthorityExample = new RoleAuthorityExample();
        roleAuthorityExample.or().andRole_idIn(roleIds);
        roleAuthorityExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        List<Integer> authorityIds = roleAuthorityMapper.selectByExample(roleAuthorityExample)
                .stream().map(RoleAuthority::getAuthorityId)
                .collect(Collectors.toList());

        AuthorityExample authorityExample = new AuthorityExample();
        authorityExample.or().andIdIn(authorityIds);
        List<Authority> authorities = authorityMapper.selectByExample(authorityExample);
        return authorities;
    }

    public List<Authority> selectByRoleId(Integer roleId){

        RoleAuthorityExample roleAuthorityExample = new RoleAuthorityExample();
        roleAuthorityExample.or().andRole_idEqualTo(roleId);
        roleAuthorityExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        List<Integer> authorityIds = roleAuthorityMapper.selectByExample(roleAuthorityExample)
                .stream().map(RoleAuthority::getAuthorityId)
                .collect(Collectors.toList());
        List<Authority> authorities = Lists.newArrayList();
        if(CollectionUtils.isEmpty(authorityIds)){
            return authorities;
        }
        AuthorityExample authorityExample = new AuthorityExample();
        authorityExample.or().andIdIn(authorityIds);
        authorityExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        authorities = authorityMapper.selectByExample(authorityExample);
        return authorities;
    }

    @Override
    public List<Authority> allPermission() {
        return authorityMapper.getAllPermission();
    }
}
